package org.gp953.user.service.impl;

import org.gp953.basic.exception.BusinessException;
import org.gp953.basic.util.StrUtils;
import org.gp953.basic.util.TextingUtil;
import org.gp953.user.domain.User;
import org.gp953.user.mapper.UserMapper;
import org.gp953.user.service.IVerifyCodeService;
import org.gp953.user.verifyconst.VerifyConst;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void registerByPhone(String phone) {
        // 验证码
        String verifyCode = "";
        // Redis中的key值由验证码字符串常量和手机号拼接而成 VerifyConst.BUSINESS_REGISTER_PREFIX +":" + phone;
        String key = "";
        // Redis中的value值，有验证码和时间戳凭借而成
        Object verifyCodeAndTimestamp = null;
        // 验证手机号
        // 手机号是否为空
        if (StringUtils.isEmpty(phone)) {
            throw new BusinessException("手机号不能为空");
        }
        User user = userMapper.queryByPhone(phone);
        // 手机号是否已经注册过了
        if (user != null) {
            throw new BusinessException("手机号已经注册过了");
        } else {
            // 获取验证码后的时间戳,需要对应的key，redis中存储的验证码格式为{常量:手机号，验证码:时间戳}
            key = VerifyConst.BUSINESS_REGISTER_PREFIX + phone;
            verifyCodeAndTimestamp = redisTemplate.opsForValue().get(key);
            if (verifyCodeAndTimestamp != null) {
                // 如果能获取就判断是否超过一分钟，没超过则提示不能重复获取
                String[] split = verifyCodeAndTimestamp.toString().split(":");
                String TimestampStr = split[1];
                long interval = System.currentTimeMillis() - Long.valueOf(TimestampStr);

                if (interval <= 1 * 60 * 1000) {
                    throw new BusinessException("请不要重复获取验证码");
                } else {
                    // 超过了就使用该验证码重新发送并把过期时间改为3分钟
                    verifyCode = split[0];
                }
            } else {
                // 如果获取不到就生成新的验证码
                verifyCode = StrUtils.getComplexRandomString(4);
            }
        }
        verifyCodeAndTimestamp = verifyCode + ":" + System.currentTimeMillis();
        redisTemplate.opsForValue().set(key, verifyCodeAndTimestamp, 3, TimeUnit.MINUTES);
        // 发送短信
//        TextingUtil.send("15982083687","您的验证码是" + verifyCode + ";请在3分钟内使用");

        // 模拟短信
        System.out.println("您的验证码是" + verifyCode + ";请在3分钟内使用");
    }
}
